package com.geek.chat.server.operation.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geek.chat.common.constant.Constants;
import com.geek.chat.common.constant.ResultCodeEnum;
import com.geek.chat.common.protobuf.ProtoMsg.ChatMsg;
import com.geek.chat.common.protobuf.ProtoMsg.Message;
import com.geek.chat.common.protobuf.builder.ProtobufBuilder;
import com.geek.chat.common.session.Session;
import com.geek.chat.server.operation.AbstractOperation;
import com.geek.chat.server.session.SessionMap;

public class ChatOperation extends AbstractOperation {
	private Logger logger = LoggerFactory.getLogger(ChatOperation.class);

	@Override
	public Integer op() {
		return Constants.OP_MESSAGE;
	}

	@Override
	public void action(Session ch, Message proto) throws Exception {
		// 聊天处理
		ChatMsg msg = proto.getChatMsg();
		logger.info("chatMsg{}", "from=" + msg.getFrom() + " , to="+msg.getTo() + " , content="+msg.getContent());
		// 获取接收方的chatID
		String to = msg.getTo();
		// int platform = msg.getPlatform();
		Session session = SessionMap.sharedInstance().getSession(to);
		if(session == null){
			Session fromSession = SessionMap.sharedInstance().getSession(msg.getFrom());
			fromSession.writeAndClose(ProtobufBuilder.buildChatResult(proto.getSeqId(), ResultCodeEnum.UNKNOW_DESTINATION));
		} else {
			// 将IM消息发送到接收方
			session.write(proto);
			Session fromSession = SessionMap.sharedInstance().getSession(msg.getFrom());
			fromSession.writeAndClose(ProtobufBuilder.buildChatResult(proto.getSeqId(), ResultCodeEnum.SUCCESS));
		}
	}

}
